from http import server
from http.server import SimpleHTTPRequestHandler
import ssl
import sys
import os

# 获取命令行参数中的端口号，默认为3000
if len(sys.argv) > 1:
    port = int(sys.argv[1])
else:
    port = 3000

print(f"Server will run on port {port}")

# 选择合适的绑定地址，监听所有可用网络接口
server_address = ('127.0.0.1', port)

# 检查证书和私钥文件是否存在
cert_path = 'D:/项目/python/web应用/server.pem'
key_path = 'D:/项目/python/web应用/server.key'

if not os.path.exists(cert_path):
    print(f"Certificate file not found: {cert_path}")
    sys.exit(1)

if not os.path.exists(key_path):
    print(f"Key file not found: {key_path}")
    sys.exit(1)

try:
    # 创建 SSL 上下文并加载证书和私钥
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    context.load_cert_chain(certfile=cert_path, keyfile=key_path)

    # 创建 HTTP 服务器实例
    httpd = server.HTTPServer(server_address, SimpleHTTPRequestHandler)
    
    # 将套接字包装成 SSL 套接字
    httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
    
    print(f"Serving HTTPS on {server_address[0]} port {port} (https://{server_address[0]}:{port}/)")
    
    # 开始服务
    httpd.serve_forever()
except Exception as e:
    print(f"An error occurred: {e}")